Option Explicit

Sub buscar()
    Dim guardar As Boolean
    Dim fr As Integer
    fr = 0
    Dim particula As String
    particula = tbParticula.Text
    Dim f, filas As Integer
    filas = frmContactos.fNumRegs
    lbRes.Clear()
    For f = 2 To filas + 1
        Dim codigo, nombre As String
        codigo = Cells(f, 1)
        nombre = Cells(f, 2)
        If particula <> "" Then
            If InStr(UCase(nombre), UCase(particula)) <> 0 Or InStr(UCase(codigo), UCase(particula)) <> 0 Then
                guardar = True
            Else
                guardar = False
            End If
        Else
            guardar = True
        End If
        If guardar Then
            lbRes.AddItem()
            lbRes.List(fr, 0) = codigo
            lbRes.List(fr, 1) = nombre
            fr = fr + 1
        End If
    Next f
    If lbRes.ListCount > 0 Then
        lbRes.ListIndex = 0
        btnSeleccionar.Enabled = True
    Else
        btnSeleccionar.Enabled = False
    End If
End Sub

Private Sub btnCancelar_Click()
    frmContactos.respuesta = ""
    Unload(Me)
End Sub

Private Sub btnSeleccionar_Click()
    seleccionar()
    Unload(Me)
End Sub

Sub seleccionar()
    Dim index As Integer
    index = lbRes.ListIndex
    If index <> -1 Then
        frmContactos.respuesta = lbRes.List(index, 0)
    End If
End Sub

Private Sub lbRes_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    seleccionar()
    Unload(Me)
End Sub

Private Sub tbParticula_Change()
    buscar()
End Sub

Public Sub UserForm_Initialize()
    frmContactos.respuesta = ""
    btnSeleccionar.Default = True
    lbRes.ColumnCount = 2
    btnSeleccionar.Enabled = False
    buscar()
    tbParticula.SetFocus()
End Sub
